﻿using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.IO;
using System.Linq;
using ST.Common.Util.Text;
using NPOI.SS.Formula.Functions;

namespace ST.Buz.Service
{
	public class VM_IMS_PartnerBasic
	{
		public int ID { get; set; }

		/// <summary>
		/// 名称
		/// </summary>
		public string Name { get; set; }

		public string Phone { get; set; }

		public string Location { get; set; }

		/// <summary>
		/// 出生日期
		/// </summary>
		public DateTime? BirthDate { get; set; }

		/// <summary>
		/// 身份证号
		/// </summary>
		public string IDCardNo { get; set; }

		/// <summary>
		/// 性别（0：未知，1：男：2：女）
		/// </summary>
		public int Gender { get; set; }

		public decimal TotalCashBalance { get; set; }

		public int TotalPointsBalance { get; set; }

		public string Code { get; set; }

		public decimal DebtTotal { get; set; }

		public decimal DebtLimit { get; set; }

		public int Type { get; set; }

		public decimal DebtAvailable { get { return DebtTotal < DebtLimit ? DebtLimit - DebtTotal : 0; } }
	}

	public class VM_MemberLookup
	{
		public int value { get; set; }

		public int ID { get; set; }

		public string Name { get; set; }

		public string PYCode { get; set; }

		public int StateNow { get; set; }

		public decimal TotalCashBalance { get; set; }

		public string Code { get; set; }

		public string Phone { get; set; }

		public decimal DebtTotal { get; set; }

		public decimal DebtLimit { get; set; }

		public int Type { get; set; }

		public decimal DebtAvailable { get { return DebtTotal < DebtLimit ? DebtLimit - DebtTotal : 0; } }
	}

	/// <summary>
	/// 只针对当前项目的扩展接口定义
	/// </summary>
	public partial interface IServicePartner
	{
		/// <summary>
		/// 获取分页列表
		/// </summary>
		PageData GetPageList(VMS_IMS_Partner searchModel, UserSession sessionCurrent);

		/// <summary>
		/// 新增或修改保存
		/// </summary>
		/// <param name="model"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		int AddOrUpdate(IMS_Partner model, UserSession sessionCurrent);

		/// <summary>
		/// 检验手机号是否可用
		/// </summary>
		/// <returns></returns>
		bool Validate(string phone, int id, UserSession sessionCurrent);

		VM_IMS_PartnerBasic GetBasic(int id, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		IMS_Partner GetViewDetail(int id, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		IMS_Partner GetEditDetail(int id, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool BatchDelete(int[] ids, UserSession sessionCurrent);

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		string GenCode(int catID, UserSession sessionCurrent);

		IMS_Partner GetBySearch(int type, string keyword, UserSession sessionCurrent);

		/// <summary>
		/// 查找（自动完成搜索）
		/// </summary>
		/// <param name="keyword"></param>
		/// <returns></returns>
		public List<VM_MemberLookup> Query(int type, string name, string pycode, string phone, string keyword, UserSession sessionCurrent, int maxShow = 100);

		UserSession RegisterOrLoginByPhone(string phone, string appID, string mpAppID, UserSession sessionCurrent);

		/// <summary>
		/// 获取当前OAuth登录默认绑定的合作伙伴ID
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		int GetDefaultPartnerID(string appID, UserSession sessionCurrent);

		/// <summary>
		/// 获取当前合作伙伴绑定的公众号ID、用户openid列表
		/// </summary>
		/// <param name="partnerID"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		List<KeyValuePair<string, string>> GetPartnerMPOpenIDList(int partnerID, UserSession sessionCurrent);
	}

	/// <summary>
	/// 只针对当前项目的扩展接口实现
	/// </summary>
	public partial class ServicePartner
	{
		private readonly IServiceSysLog serviceSysLog;
		private readonly IServiceSysBuzRowNum serviceSysBuzRowNum;

		public ServicePartner(BuzContext ctx,
			IServiceSysLog _serviceSysLog,
			IServiceSysBuzRowNum _serviceSysBuzRowNum,
			ILogger<ServicePartner> log)
		{
			serviceSysLog = _serviceSysLog;
			serviceSysBuzRowNum = _serviceSysBuzRowNum;

			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_IMS_Partner searchModel, UserSession sessionCurrent)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();

				var query = (from u in context.Partner
							 join cat in context.SysEnumCode on u.CatID equals cat.ID into cattmp
							 from catall in cattmp.DefaultIfEmpty()
							 select new VML_IMS_Partner()
							 {
								 ID = u.ID,
								 CatID = u.CatID,
								 CatName = catall.Name,
								 Type = u.Type,
								 Code = u.Code,
								 Name = u.Name,
								 Sort = u.Sort,
								 StateNow = u.StateNow,
								 Province = u.Province,
								 City = u.City,
								 District = u.District,
								 Town = u.Town,
								 Location = u.Location,
								 AddManName = u.AddManName,
								 AddDate = u.AddDate,
								 ContactMan = u.ContactMan,
								 ContactPhone = u.ContactPhone,
								 PYCode = u.PYCode,
								 Phone = u.Phone,
								 Gender = u.Gender,
								 BirthDate = u.BirthDate,
								 Fax = u.Fax,
								 TotalCashBalance = u.TotalCashBalance,
								 TotalCashIn = u.TotalCashIn,
								 OrgID = u.OrgID
							 }).AsNoTracking();
				if (!string.IsNullOrWhiteSpace(searchModel.code))
				{
					query = query.Where(m => m.Code == searchModel.code);
				}
				if (!string.IsNullOrWhiteSpace(searchModel.name))
				{
					query = query.Where(m => EF.Functions.Like(m.Name, "%" + searchModel.name + "%"));
				}
				if (!string.IsNullOrWhiteSpace(searchModel.pycode))
				{
					query = query.Where(m => EF.Functions.Like(m.PYCode, searchModel.pycode + "%"));
				}
				if (!string.IsNullOrWhiteSpace(searchModel.phone))
				{
					query = query.Where(m => searchModel.phone == m.Phone || m.Phone.EndsWith(searchModel.phone));
				}
				if (!string.IsNullOrWhiteSpace(searchModel.contactman))
				{
					query = query.Where(m => EF.Functions.Like(m.ContactMan, "%" + searchModel.contactman + "%"));
				}
				if (!string.IsNullOrWhiteSpace(searchModel.contactphone))
				{
					query = query.Where(m => EF.Functions.Like(m.ContactPhone, "%" + searchModel.contactphone + "%"));
				}
				if (searchModel.type != null && searchModel.type.Length > 0)
				{
					query = searchModel.type.Length == 1 ? query.Where(m => m.Type == searchModel.type[0]) : query.Where(m => searchModel.type.Contains(m.Type));
				}
				if (searchModel.catid != null && searchModel.catid.Length > 0)
				{
					query = searchModel.catid.Length == 1 ? query.Where(m => m.CatID == searchModel.catid[0]) : query.Where(m => searchModel.catid.Contains(m.CatID));
				}
				if (searchModel.orgids != null && searchModel.orgids.Length > 0)
				{
					query = searchModel.orgids.Length == 1 ? query.Where(m => m.OrgID == searchModel.orgids[0]) : query.Where(m => searchModel.orgids.Contains(m.OrgID));
				}
				switch (searchModel.sortby)
				{
					case "Code":
						////数据库分页，不支持多表
						//query = query.OrderByDescending(e => EF.Property<object>(e, sortOrder));
						////内存分页
						////query = query.OrderByDescending(e => e.GetType().GetProperty(sortOrder).GetValue(e, null));
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Code) : query.OrderByDescending(e => e.Code);
						break;
					case "Name":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
						break;
					case "StateNow":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.StateNow) : query.OrderByDescending(e => e.StateNow);
						break;
					case "ID":
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
					default:
						query = query.OrderBy(e => e.Sort).ThenBy(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 获取详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public IMS_Partner GetViewDetail(int id, UserSession sessionCurrent)
		{
			IMS_Partner model = null;
			try
			{
				var result = (from m in context.Partner
							  join cat in context.SysEnumCode on m.CatID equals cat.ID into cattmp
							  from catall in cattmp.DefaultIfEmpty()
							  where m.ID == id
							  select new { Model = m, CatName = catall.Name, LevelName = catall.Name }).SingleOrDefault();
				if (result == null || result.Model == null)
				{
					throw new EntityNotFoundException("未找到id为" + id + "的记录或记录已删除");
				}
				model = result.Model;
				//model.CatName = result.LevelName;
				model.CatName = result.CatName;
			}
			catch (EntityNotFoundException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return model;
		}

		/// <summary>
		/// 获取详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public IMS_Partner GetEditDetail(int id, UserSession sessionCurrent)
		{
			return GetViewDetail(id, sessionCurrent);
		}

		/// <summary>
		/// 新增或修改保存
		/// </summary>
		public int AddOrUpdate(IMS_Partner model, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (model == null)
				{
					throw new BuzException("参数不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;

						if (model.ID > 0)
						{
							if (!string.IsNullOrEmpty(model.Phone) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Phone == model.Phone && m.ID != model.ID && m.Type == model.Type))
							{
								throw new BuzException("手机号码已存在");
							}
							if (!string.IsNullOrEmpty(model.Code) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Code == model.Code && m.ID != model.ID && m.Type == model.Type))
							{
								throw new BuzException("编号已存在");
							}
							if (!string.IsNullOrEmpty(model.Name) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Name == model.Name && m.ID != model.ID && m.Type == model.Type))
							{
								throw new BuzException("名称已存在");
							}
							if (string.IsNullOrEmpty(model.Code))
							{
								model.Code = GenCodeWithinTrans(model.CatID, sessionCurrent);
							}
							Update(model);
						}
						else
						{
							model.AddDate = dtNow;
							model.AddManID = sessionCurrent.UserID;
							model.AddManName = sessionCurrent.UserName;
							model.OrgID = sessionCurrent.OrgID;
							model.StateNow = (int)PartnerState.正常;

							if (!string.IsNullOrEmpty(model.Phone) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Phone == model.Phone && m.Type == model.Type))
							{
								throw new BuzException("手机号码已存在");
							}
							if (!string.IsNullOrEmpty(model.Code) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Code == model.Code && m.Type == model.Type))
							{
								throw new BuzException("编号已存在");
							}
							if (!string.IsNullOrEmpty(model.Name) && context.Partner.Any(m => m.OrgID == sessionCurrent.OrgID && m.Name == model.Name && m.Type == model.Type))
							{
								throw new BuzException("名称已存在");
							}
							if (string.IsNullOrEmpty(model.Code))
							{
								model.Code = GenCodeWithinTrans(model.CatID, sessionCurrent);
							}
							Add(model);
						}

						#endregion

						trans.Commit();

						return model.ID;
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 检验手机号是否可用
		/// </summary>
		/// <returns></returns>
		public bool Validate(string phone, int id, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (string.IsNullOrEmpty(phone))
				{
					throw new BuzException("手机号不能为空");
				}
				if (id > 0)
				{
					return !context.Partner.Any(m => m.Phone == phone && m.ID != id);
				}
				else
				{
					return !context.Partner.Any(m => m.Phone == phone);
				}
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "检验手机号出错");
				throw new BuzException("检验手机号失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public VM_IMS_PartnerBasic GetBasic(int id, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				var result = (from m in context.Partner
							  where m.ID == id
							  select new VM_IMS_PartnerBasic()
							  {
								  ID = m.ID,
								  BirthDate = m.BirthDate,
								  Gender = m.Gender,
								  IDCardNo = m.IDCardNo,
								  Code = m.Code,
								  Location = m.Location,
								  Name = m.Name,
								  Phone = m.Phone,

								  TotalCashBalance = m.TotalCashBalance,
								  Type = m.Type,
								  TotalPointsBalance = m.TotalPointsBalance,
								  DebtLimit = m.DebtLimit,
							  }).AsNoTracking().SingleOrDefault();
				return result;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取信息出错");
				throw new BuzException("获取信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 删除具体操作
		/// </summary>
		/// <param name="id"></param>
		/// <param name="ip"></param>
		/// <param name="dtNow"></param>
		/// <param name="sessionCurrent"></param>
		protected void DeleteWithinTrans(int id, string ip, DateTime dtNow, UserSession sessionCurrent)
		{
			var modelOld = Get(id);
			//switch (modelOld.Type)
			//{
			//	case (int)PartnerType.供应商:
			//		{
			//			if (context.FinancePayDue.Any(m => m.PartnerID == id))
			//			{
			//				throw new BuzException("供应商【" + modelOld.Name + "】已有业务数据，不能删除");
			//			}
			//		}
			//		break;
			//	case (int)PartnerType.供应商和客户:
			//		{
			//			if (context.FinancePayDue.Any(m => m.PartnerID == id) || context.FinanceRecvDue.Any(m => m.PartnerID == id))
			//			{
			//				throw new BuzException("往来单位【" + modelOld.Name + "】已有业务数据，不能删除");
			//			}
			//		}
			//		break;
			//	case (int)PartnerType.客户:
			//		{
			//			if (context.FinanceRecvDue.Any(m => m.PartnerID == id))
			//			{
			//				throw new BuzException("客户【" + modelOld.Name + "】已有业务数据，不能删除");
			//			}
			//		}
			//		break;
			//}
		
			Delete(modelOld);

			serviceSysLog.Add(sessionCurrent, ip, $"批量删除往来单位信息，原信息：" + Newtonsoft.Json.JsonConvert.SerializeObject(modelOld), dtNow);
		}

		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success;
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();
						DeleteWithinTrans(id, ip, dtNow, sessionCurrent);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除往来单位信息出错");
				throw new BuzException("删除往来单位信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		/// <summary>
		/// 批量删除
		/// </summary>
		/// <returns></returns>
		public bool BatchDelete(int[] ids, UserSession sessionCurrent)
		{
			bool success;
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				if (ids == null || ids.Length == 0)
				{
					throw new BuzException("参数不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						foreach (int id in ids)
						{
							DeleteWithinTrans(id, ip, dtNow, sessionCurrent);
						}
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "批量删除往来单位信息出错");
				throw new BuzException("批量删除往来单位信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		public string GenCodeWithinTrans(int catID, UserSession sessionCurrent)
		{
			return serviceSysBuzRowNum.GetNextWithinTrans(catID, BuzRowNumType.会员编号.ToString());
		}

		public string GenCode(int catID, UserSession sessionCurrent)
		{
			return serviceSysBuzRowNum.GetNext(catID, BuzRowNumType.会员编号.ToString());
		}

		public IMS_Partner GetBySearch(int type, string keyword, UserSession sessionCurrent)
		{
			IMS_Partner model = null;
			try
			{
				model = (from m in context.Partner
						 join cat in context.SysEnumCode on m.CatID equals cat.ID into cattmp
						 from catall in cattmp.DefaultIfEmpty()
						 where m.Type == type && (m.Code == keyword || m.Phone == keyword || keyword.Length >= 4 && m.Phone.EndsWith(keyword))
						 select new IMS_Partner()
						 {
							 ID = m.ID,
							 CatID = m.CatID,
							 CatName = catall.Name,
							 Type = m.Type,
							 Code = m.Code,
							 Name = m.Name,
							 Sort = m.Sort,
							 StateNow = m.StateNow,
							 Province = m.Province,
							 City = m.City,
							 District = m.District,
							 Town = m.Town,
							 Location = m.Location,
							 AddManName = m.AddManName,
							 AddDate = m.AddDate,
							 ContactMan = m.ContactMan,
							 ContactPhone = m.ContactPhone,
							 PYCode = m.PYCode,
							 Phone = m.Phone,
							 Gender = m.Gender,
							 BirthDate = m.BirthDate,
							 Fax = m.Fax,
							 TotalCashBalance = m.TotalCashBalance,
							 TotalCashIn = m.TotalCashIn,
						 }).FirstOrDefault();
			}
			catch (EntityNotFoundException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return model;
		}

		/// <summary>
		/// 查找（自动完成搜索）
		/// </summary>
		/// <param name="keyword"></param>
		/// <returns></returns>
		public List<VM_MemberLookup> Query(int type, string name, string pycode, string phone, string keyword, UserSession sessionCurrent, int maxShow = 100)
		{
			try
			{
				var query = from m in context.Partner
							where m.StateNow == (int)PartnerState.正常 && m.Type == type
							&& m.OrgID == sessionCurrent.OrgID
							select new VM_MemberLookup()
							{
								value = m.ID,
								Code = m.Code,
								ID = m.ID,
								Name = m.Name,
								Phone = m.Phone,
								PYCode = m.PYCode,
								StateNow = m.StateNow,
								TotalCashBalance = m.TotalCashBalance,
								DebtLimit = m.DebtLimit,
								Type = m.Type,
							};
				if (!string.IsNullOrEmpty(phone))
				{
					query = query.Where(m => phone == m.Phone || m.Phone.EndsWith(phone));
				}
				else if (!string.IsNullOrEmpty(name))
				{
					query = query.Where(m => m.Name.Contains(name));
				}
				else if (!string.IsNullOrEmpty(pycode))
				{
					query = query.Where(m => m.PYCode.Contains(pycode));
				}
				else if (!string.IsNullOrWhiteSpace(keyword))
				{
					query = query.Where(m => m.PYCode.Contains(keyword) || m.Name.Contains(keyword));
				}
				//query = query.OrderBy(e => e.catid);
				return query.Take(maxShow).ToList();
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "查找出错");
				throw new BuzException("查找失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		public UserSession RegisterOrLoginByPhone(string phone, string appID, string mpAppID, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (string.IsNullOrEmpty(phone))
				{
					throw new BuzException("手机号不能为空");
				}
				if (string.IsNullOrEmpty(appID))
				{
					throw new BuzException("小程序ID不能为空");
				}
				if (string.IsNullOrEmpty(sessionCurrent.OpenID))
				{
					throw new BuzException("小程序未登录");
				}
				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();
						var oauth = context.SysOAuth.SingleOrDefault(x => x.AppID == appID && x.OpenID == sessionCurrent.OpenID);
						if (oauth == null)
						{
							throw new BuzException("未找到小程序授权信息");
						}
						//var partner = context.Partner.SingleOrDefault(p => p.Type == (int)PartnerType.会员 && p.Phone == phone);
						//if (partner == null)
						//{
						//	partner = new IMS_Partner()
						//	{
						//		Type = (int)PartnerType.会员,
						//		AddDate = dtNow,
						//		AddManID = sessionCurrent.UserID,
						//		AddManName = sessionCurrent.UserName,
						//		Code = "",
						//		Name = oauth.NickName,
						//		OrgID = sessionCurrent.OrgID,
						//		Phone = phone,
						//		StateNow = (int)PartnerState.正常,
						//	};
						//	context.Partner.Add(partner);
						//	context.SaveChanges();
						//}

						//var partnerOAuth = context.PartnerOAuth.SingleOrDefault(x => x.OAuthID == oauth.ID && x.PartnerID == partner.ID);
						//if (partnerOAuth == null)
						//{
						//	partnerOAuth = new IMS_PartnerOAuth()
						//	{
						//		OAuthID = oauth.ID,
						//		PartnerID = partner.ID,
						//		AddDate = dtNow,
						//		Preferred = true
						//	};
						//	context.PartnerOAuth.Add(partnerOAuth);
						//	context.SaveChanges();
						//}
						var user = context.SysUser.SingleOrDefault(x => x.ID == oauth.UserID);
						if (user == null)
						{
							throw new BuzException("未找到小程序相关的用户信息");
						}
						//if (user.StateNow == (int)UserState.未绑定)
						//{
						//	user.Name = partner.Name;
						//	user.Phone = partner.Phone;
						//	user.Mobile = partner.Phone;
						//	user.StateNow = (int)UserState.正常;
						//	context.SaveChanges();
						//}
						sessionCurrent.State = user.StateNow;
						sessionCurrent.UserName = user.Name;
						//sessionCurrent.PartnerID = partnerOAuth.PartnerID;
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "会员登录/注册出错");
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "会员登录/注册出错");
				throw new BuzException("会员登录/注册失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return sessionCurrent;
		}

		/// <summary>
		/// 获取当前OAuth登录默认绑定的合作伙伴ID
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public int GetDefaultPartnerID(string appID, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (string.IsNullOrEmpty(appID))
				{
					throw new BuzException("appid不能为空");
				}
				if (string.IsNullOrEmpty(sessionCurrent.OpenID))
				{
					throw new BuzException("当前登录用户openid不能为空");
				}
				var result = (from po in context.PartnerOAuth
							  join o in context.SysOAuth on po.OAuthID equals o.ID
							  where o.AppID == appID && o.OpenID == sessionCurrent.OpenID
							  select po).ToList();
				if (result != null && result.Count > 0)
				{
					var def = result.FirstOrDefault(x => x.Preferred);
					if (def != null)
					{
						return def.PartnerID;
					}
					return result[0].PartnerID;
				}
				return 0;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取默认绑定会员账户出错");
				throw new BuzException("获取默认绑定会员账户失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取当前合作伙伴绑定的公众号用户列表
		/// </summary>
		/// <param name="partnerID"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public List<KeyValuePair<string, string>> GetPartnerMPOpenIDList(int partnerID, UserSession sessionCurrent)
		{
			try
			{
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (partnerID <= 0)
				{
					throw new BuzException("合作伙伴ID不能为空");
				}
				var result = (from po in context.PartnerOAuth
							  join xo in context.SysOAuth on po.OAuthID equals xo.ID
							  join mo in context.SysOAuth on xo.RelatedOAuthID equals mo.ID
							  where po.PartnerID == partnerID
							  select new KeyValuePair<string, string>(mo.AppID, mo.OpenID)).ToList();
				return result;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取绑定用户列表出错");
				throw new BuzException("获取绑定用户列表失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}
	}
}